//
//  RHLocalFirmwareListVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/17.
//

#import "RHLocalFirmwareListVC.h"
#import "RHFirmwareUpgradeCell.h"
#import "RHAboutOneUpgradeController.h"
#import "RHNavigationController.h"
#import "RHLocalFirmwareDetailVC.h"

@interface RHLocalFirmwareListVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *footView;

@property (nonatomic ,strong) NSArray *upgradeArr;

@property (nonatomic ,strong) NSMutableArray *selectFirmwares;

@property (nonatomic ,strong) QMUILabel *firmwareLab;

@property (nonatomic, assign) NSInteger updateIndex;

@property (nonatomic, strong) QMUINavigationButton *rightBtn;

@property (nonatomic, strong) QMUIButton *selectAllBtn;

@property (nonatomic, assign) BOOL hasSelected;

@end

@implementation RHLocalFirmwareListVC

-(NSMutableArray *)selectFirmwares
{
    if(!_selectFirmwares){
        _selectFirmwares = [NSMutableArray array];
    }
    return _selectFirmwares;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self.navigationItem setTitle:@"固件升级".rh_localized];
    [self getDeviceFirmwareUpgradeList];
    [self setupUI];
}

-(void)getDeviceFirmwareUpgradeList
{
    [QMUITips showLoadingInView:self.view];
    [RHFirmwareModel startGetWithCompletionAPIKey:H_endUserUpgradeList argument:@{@"deviceId":ValidNullData(@"DC10001XF1010050")} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.hasSelected = NO;
            self.upgradeArr = resultModel.data;
            [self.tableView reloadData];
            [self.tableView endHeaderRefresh];
        }
        
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
        }];
}

- (void)setupUI{
   
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHFirmwareUpgradeCell class] forCellReuseIdentifier:@"RHFirmwareUpgradeCell"];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImage:[UIImage imageNamed:@"nodata_icon_1"] titleStr:@"没有数据".rh_localized detailStr:@""];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0,0, 0));
    }];
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        weakSelf.firmwareLab.text = @"";
        [weakSelf.selectFirmwares removeAllObjects];
        weakSelf.rightBtn.selected = YES;
        [weakSelf selectAllAction:weakSelf.rightBtn];
        [weakSelf getDeviceFirmwareUpgradeList];
    }];
    
    _footView = [[UIView alloc] init];
    _footView.layer.cornerRadius = 15;
    _footView.layer.shadowColor = [UIColor blackColor].CGColor;
    
    [_footView setBackgroundColor:kCOLOR_HEX(@"ffffff")];
    [self.view addSubview:_footView];
    
    QMUIButton *selectAllBtn = [[QMUIButton alloc]init];
    [selectAllBtn setImage:[UIImage imageNamed:@"ugrade_cancel"] forState:UIControlStateNormal];
    [selectAllBtn setImage:[UIImage imageNamed:@"ugrade_select"] forState:UIControlStateSelected];
    [_footView addSubview:selectAllBtn];
    self.selectAllBtn = selectAllBtn;
    
    QMUILabel *firmwareLab = [[QMUILabel alloc] init];
    firmwareLab.numberOfLines = 0;
    [firmwareLab setTextAlignment:NSTextAlignmentLeft];
    [firmwareLab setTextColor:kCOLOR_HEX(@"3F4443")];
    [firmwareLab setFont:[UIFont systemFontOfSize:13]];
    [firmwareLab setText:[NSString stringWithFormat:@"%@:%ld",@"已选".rh_localized,self.selectFirmwares.count]];
    [_footView addSubview:firmwareLab];
    self.firmwareLab = firmwareLab;
    
    
    QMUIButton *upgradeBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [upgradeBtn setGradientBackgroundWithColors:@[kCOLOR_HEX(@"6AD785"),kCOLOR_HEX(@"5ECBB7")] locations:@[@(0),@(1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5)];
    [upgradeBtn setTitle:@"升级".rh_localized forState:UIControlStateNormal];
    [upgradeBtn setCornerRadius:8];
    
    [upgradeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [upgradeBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [_footView addSubview:upgradeBtn];
    
    
    [_footView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.height.offset(60+kSafe_bottom);
        make.bottom.mas_offset(60+kSafe_bottom);
    }];
    
    [selectAllBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(30);
        make.left.mas_offset(25);
        make.centerY.equalTo(upgradeBtn);
    }];
    
    [firmwareLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectAllBtn.mas_right).offset(15);
        make.centerY.equalTo(selectAllBtn);
    }];
    
    [upgradeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.right.mas_offset(-20);
        make.width.offset(kScaleW(90));
        make.height.offset(kScaleW(40));
    }];
    
    
    
    [[selectAllBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        weakSelf.selectAllBtn.selected = weakSelf.selectAllBtn.selected;
        [weakSelf selectAllAction:weakSelf.rightBtn];
    }];
    [[upgradeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        weakSelf.updateIndex = 0;
       
    }];
}

#pragma mark - Action Method
- (void)learnMoreAction:(RHFirmwareModel*)firmwareModel{
    RHAboutOneUpgradeController *vc = [[RHAboutOneUpgradeController alloc] init];
    vc.firmwareModel = firmwareModel;
    RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)selectAllAction:(QMUINavigationButton*)button
{
    if(self.upgradeArr.count == 0)return;
    button.selected = !button.selected;
    if(button.selected){
        [self.selectFirmwares removeAllObjects];
        for (RHFirmwareModel *firmwareModel in self.upgradeArr) {
            firmwareModel.isClicked = YES;
            //异常固件不能添加
            if(firmwareModel.normal != 2){
                firmwareModel.isSelected = YES;
                [self.selectFirmwares addObject:firmwareModel];
            }
        }
        
    }else{
        for (RHFirmwareModel *firmwareModel in self.upgradeArr) {
            firmwareModel.isSelected = NO;
        }
        [self.selectFirmwares removeAllObjects];
    }
    
    [self.tableView reloadData];
    self.selectAllBtn.selected = button.selected;
    [self.firmwareLab setText:[NSString stringWithFormat:@"%@:%ld",@"已选".rh_localized,self.selectFirmwares.count]];
    self.hasSelected = YES;
    
    [_footView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(0);
    }];
    
}






#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.upgradeArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return kBottomToolBar+44;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHFirmwareUpgradeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHFirmwareUpgradeCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.firmwareModel = self.upgradeArr[indexPath.row];
    kWeakSelf;
    cell.learnMoreBlock = ^{
        [weakSelf learnMoreAction:weakSelf.upgradeArr[indexPath.row]];
    };
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
   
    RHFirmwareModel *model = self.upgradeArr[indexPath.row];
    if(model.normal == 2){
        __block NSMutableString *title = [NSMutableString string];
        __block NSString *currentVersion = @"";
        [model.sn enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([obj[@"normal"] integerValue] == 2){
                
                if(obj[@"sn"]){
                    [title appendString:[NSString stringWithFormat:@"SN:%@   V:%@",obj[@"sn"],obj[@"currentVersion"]]];
                    [title appendString:@"\n"];
                }
                
                currentVersion = obj[@"currentVersion"];
            }
        }];
       
        QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:@"此固件异常".rh_localized message:[NSString stringWithFormat:@"%@",title] preferredStyle:QMUIAlertControllerStyleAlert];
        QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:sure];
        [alertVC showWithAnimated:YES];
        return;
    }
    
    //本地蓝牙升级
   
    RHLocalFirmwareDetailVC *detailVC = [[RHLocalFirmwareDetailVC alloc]init];
    detailVC.firmwareModel = model;
    [self.navigationController pushViewController:detailVC animated:YES];
       
  
    
   
}



@end
